class luoma{
    public static void main(String[] agrs){
        Solution a = new Solution();
        a.romanToInt("MDCLVIII");
        int b = a.num;
        System.out.println(b);
    }
}

class Solution {
    int num ;

    public int romanToInt(String s) {
        String[] arr = s.split("");
        String[] brr = new String[]{"I", "V", "X", "L", "C", "D", "M"};
        String[] crr = new String[]{"1", "5", "10", "50", "100", "500", "1000"};
        int[] drr = new int[arr.length];
        //int V = 5,X = 10,L = 50,C = 100,D = 500,M = 1000;
        for (int i = 0; i <= arr.length - 1; i++) {
            for (int j = 0; j <= brr.length - 1; j++) {
                if (arr[i].equals(brr[j])) {
                    arr[i] = crr[j];
                    drr[i] = Integer.parseInt(arr[i]);
                }
            }
        }
        int k = 0;
        if(arr.length>1 ){
            if (drr[0] > drr[1]) {
                for (int i = arr.length - 1; i > 0; i--) {
                    if (drr[i] > drr[i - 1] && i > 1) {
                        //后大
                        k += drr[i] - drr[i - 1];
                        i--;
                    } else {
                        k += drr[i];
                    }
                }
                num = k + drr[0];
                return num;
            }
            if (drr[0] < drr[1]) {
                for (int i = arr.length-1; i>0 ; i--) {
                    if(drr[i]>drr[i-1] && i>1){
                        //后大
                        k+=drr[i]-drr[i-1];
                        i--;
                    }else {
                        k+=drr[i];
                    }
                }
                num = k-drr[0];
                return num;
            }
            if (drr[0]==drr[1]) {
                for (int i = arr.length - 1; i > 0; i--) {
                    if (drr[i] > drr[i - 1] && i > 1) {
                        //后大
                        k += drr[i] - drr[i - 1];
                        i--;
                    } else {
                        k += drr[i];
                    }
                }
                num = (k + drr[0]);
                return num;
            }
        }
        num = drr[0];
        return num;
    }
}
